//
//  YWWriteGrabTroubleInfoViewController.m
//  maintain
//
//  Created by kyo on 16/12/13.
//  Copyright © 2016年 ewin. All rights reserved.
//

#import "YWWriteGrabTroubleInfoViewController.h"
#import "UIColor+CustomColors.h"
#import "YWMacro.h"
#import "YWConst.h"
#import "YWCommonTool.h"
#import "UIView+Extension.h"
#import "YWHandler.h"
#import "MBProgressHUD.h"
#import "WMHttpTool.h"
#import "YWMission.h"
#import "YWMissionManager.h"
#import "YWCirculationInfo.h"
#import "YWCirculationManager.h"
#import "YWLoginUser.h"
#import "YWLoginTool.h"
#import "MJExtension.h"
#import "YWEwinManager.h"
#import "YWReportTroubleModel.h"
#import "YWTroubleMissionModel.h"
#import "YWTroubleMissionManager.h"
#import "YWReportTroubleManager.h"
#import "YWCirculationManager.h"

static CGFloat const kMargin = 15;
static CGFloat const kGap = 15;
static CGFloat const kLabelWidth = 70;
static CGFloat const kLabelHeight = 40;
static CGFloat const kNoteTextViewH = 65;
static CGFloat const kDatePickerViewH = 216;
#define kButtonWidth SCREEN_WIDTH-kMargin*3-kLabelWidth
#define KNoteTextMax 100

@interface YWWriteGrabTroubleInfoViewController ()<UITextViewDelegate>{
    CGFloat originalBgViewY;
}
@property (nonatomic, strong) UIView* bgView;
@property (nonatomic, strong) UILabel *memberLabel;
@property (nonatomic, strong) UIButton* memberButton;
@property (nonatomic, strong) UILabel* dateLabel;
@property (nonatomic, strong) UIButton *dateButton;
@property (nonatomic, strong) UILabel *noteLabel;
@property (nonatomic, strong) UITextView *noteTextView;
@property (nonatomic, strong) UILabel *inputTextCount;
@property (nonatomic, strong) UIButton *sureButton;

@property (nonatomic, strong) UIDatePicker *datePicker;
@property (nonatomic, strong) NSDateFormatter *dateFormatter;
@property (nonatomic, assign) BOOL isShowDatePicker;

@property (nonatomic, weak) MBProgressHUD* HUD;
@end

@implementation YWWriteGrabTroubleInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = NSLocalizedString(@"grabTroubleBill", nil);
    self.view.backgroundColor = [UIColor customBackgroudColor];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"cancel", nil) style:UIBarButtonItemStylePlain target:self action:@selector(handleCancelEvent:)];
    [self layoutMySubViews];
    originalBgViewY = self.bgView.y;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (UIView*)bgView
{
    if (!_bgView) {
        CGFloat bgViewH = kGap*3+20+kLabelHeight*3+kNoteTextViewH;
        UIView* bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, bgViewH)];
        bgView.userInteractionEnabled = YES;
        self.bgView = bgView;
        [self.view addSubview:bgView];
    }
    return _bgView;
}

-(UILabel *)memberLabel{
    if (!_memberLabel) {
        UILabel *menberLabel = [[UILabel alloc] init];
        menberLabel.textColor = [UIColor blackColor];
        menberLabel.font = kContentFont;
        menberLabel.text = [NSString stringWithFormat:@"%@:",NSLocalizedString(@"executor", nil)];
        [self.bgView addSubview:menberLabel];
        _memberLabel = menberLabel;
    }
    return _memberLabel;
}

-(UIButton *)memberButton{
    if (!_memberButton) {
        UIButton* memberBtn = [UIButton buttonWithType:UIButtonTypeSystem];
        YWLoginUser *currentUser = [YWLoginTool loginUser];
        [memberBtn setTitle:currentUser.userName?:@"" forState:UIControlStateNormal];
        [memberBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [memberBtn setBackgroundColor:[UIColor whiteColor]];
        memberBtn.titleLabel.font = kContentFont;
        memberBtn.layer.borderColor = [UIColor lightGrayColor].CGColor;
        memberBtn.layer.borderWidth = 1.0;
        memberBtn.clipsToBounds = YES;
        memberBtn.layer.cornerRadius = 4.0;
        [self.bgView addSubview:memberBtn];
        _memberButton = memberBtn;
    }
    return _memberButton;
}

-(UILabel *)dateLabel{
    if (!_dateLabel) {
        UILabel *dateLabel = [[UILabel alloc] init];
        dateLabel.textColor = [UIColor blackColor];
        dateLabel.font = kContentFont;
        dateLabel.text = [NSString stringWithFormat:@"%@:",NSLocalizedString(@"deadline", nil)];
        [self.bgView addSubview:dateLabel];
        _dateLabel = dateLabel;
    }
    return _dateLabel;
}

-(UIButton *)dateButton{
    if (!_dateButton) {
        UIButton* dateBtn = [UIButton buttonWithType:UIButtonTypeSystem];
        NSDateFormatter *todayFormat = [self dateFormatter];
        NSDate *date = [NSDate date];
        NSString *today = [todayFormat stringFromDate:date];
        [dateBtn setTitle:today forState:UIControlStateNormal];
        [dateBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [dateBtn setBackgroundColor:[UIColor whiteColor]];
        dateBtn.titleLabel.font = kContentFont;
        dateBtn.layer.borderColor = [UIColor lightGrayColor].CGColor;
        dateBtn.layer.borderWidth = 1.0;
        dateBtn.clipsToBounds = YES;
        dateBtn.layer.cornerRadius = 4.0;
        UIImage *btnImage = [UIImage imageNamed:@"scan_arrow"];
        btnImage = [btnImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        [dateBtn setImage:btnImage forState:UIControlStateNormal];
        dateBtn.imageView.contentMode = UIViewContentModeCenter;
        dateBtn.imageView.clipsToBounds = NO;
        dateBtn.imageEdgeInsets = UIEdgeInsetsMake(0, kButtonWidth-20, 0, 0);
        dateBtn.titleEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 10);
        [dateBtn addTarget:self action:@selector(handleDateButtonEvent) forControlEvents:UIControlEventTouchUpInside];
        [self.bgView addSubview:dateBtn];
        _dateButton = dateBtn;
    }
    return _dateButton;
}

- (NSDateFormatter*)dateFormatter
{
    if (!_dateFormatter) {
        _dateFormatter = [[NSDateFormatter alloc] init];
        [_dateFormatter setDateFormat:@"yyyy-MM-dd"];
    }
    return _dateFormatter;
}

-(UIDatePicker *)datePicker{
    if (!_datePicker) {
        _datePicker=[[UIDatePicker alloc]init];
        [_datePicker setBackgroundColor:[UIColor whiteColor]];
        _datePicker.datePickerMode = UIDatePickerModeDate;
        _datePicker.locale =[NSLocale localeWithLocaleIdentifier:@"zh"];
        [_datePicker setMinimumDate:[NSDate date]];
        [_datePicker addTarget:self action:@selector(dateChanged:) forControlEvents:UIControlEventValueChanged];
        [self.view addSubview:_datePicker];
    }
    return _datePicker;
}

-(UILabel *)noteLabel{
    if (!_noteLabel) {
        UILabel *noteLabel = [[UILabel alloc] init];
        noteLabel.textColor = [UIColor blackColor];
        noteLabel.font = kContentFont;
        noteLabel.text = [NSString stringWithFormat:@"%@:",NSLocalizedString(@"note", nil)];
        [self.bgView addSubview:noteLabel];
        _noteLabel = noteLabel;
    }
    return _noteLabel;
}

-(UITextView *)noteTextView{
    if (!_noteTextView) {
        UITextView* textView = [[UITextView alloc]init];
        textView.layer.borderColor = [UIColor lightGrayColor].CGColor;
        textView.layer.borderWidth = 1.0;
        textView.clipsToBounds = YES;
        textView.layer.cornerRadius = 4.0;
        textView.font = kContentFont;
        textView.delegate = self;
        [self.bgView addSubview:textView];
        _noteTextView = textView;
    }
    return _noteTextView;
}

-(UILabel *)inputTextCount{
    if (!_inputTextCount) {
        UILabel *inputTextCount = [[UILabel alloc] init];
        inputTextCount.textColor = [UIColor customTextGrayColor];
        inputTextCount.font = kContentFont;
        inputTextCount.text = @"0/100";
        inputTextCount.textAlignment = NSTextAlignmentRight;
        [self.bgView addSubview:inputTextCount];
        _inputTextCount = inputTextCount;
    }
    return _inputTextCount;
}

-(UIButton *)sureButton{
    if (!_sureButton) {
        UIButton* sureButton = [UIButton buttonWithType:UIButtonTypeSystem];
        [sureButton setTitle:NSLocalizedString(@"sure", nil) forState:UIControlStateNormal];
        [sureButton setTitleColor:[UIColor customBlueColor] forState:UIControlStateNormal];
        [sureButton setBackgroundColor:[UIColor whiteColor]];
        sureButton.titleLabel.font = kContentFont;
        sureButton.layer.borderColor = [UIColor customBlueColor].CGColor;
        sureButton.layer.borderWidth = 1.0;
        sureButton.clipsToBounds = YES;
        sureButton.layer.cornerRadius = 4.0;
        [sureButton addTarget:self action:@selector(clickSureButton) forControlEvents:UIControlEventTouchUpInside];
        [self.bgView addSubview:sureButton];
        _sureButton = sureButton;
    }
    return _sureButton;
}

-(void)layoutMySubViews{
    _isShowDatePicker = NO;
    
    [self.memberLabel setFrame:CGRectMake(kMargin, kGap, kLabelWidth, kLabelHeight)];
    [self.memberButton setFrame:CGRectMake(CGRectGetMaxX(self.memberLabel.frame)+kMargin, kGap, kButtonWidth, kLabelHeight)];
    [self.dateLabel setFrame:CGRectMake(kMargin, CGRectGetMaxY(self.memberLabel.frame)+kGap, kLabelWidth, kLabelHeight)];
    [self.dateButton setFrame:CGRectMake(CGRectGetMaxX(self.dateLabel.frame)+kMargin, CGRectGetMaxY(self.memberLabel.frame)+kGap, kButtonWidth, kLabelHeight)];
    CGFloat inputLabelW = 100;
    CGFloat inputLabelH = 20;
    [self.inputTextCount setFrame:CGRectMake(SCREEN_WIDTH-kMargin-inputLabelW-2, CGRectGetMaxY(self.dateButton.frame), inputLabelW, inputLabelH)];
    [self.noteLabel setFrame:CGRectMake(kMargin, CGRectGetMaxY(self.dateLabel.frame)+inputLabelH, kLabelWidth, kNoteTextViewH)];
    [self.noteTextView setFrame:CGRectMake(CGRectGetMaxX(self.noteLabel.frame)+kMargin, CGRectGetMaxY(self.dateLabel.frame)+inputLabelH, kButtonWidth, kNoteTextViewH)];
    [self.sureButton setFrame:CGRectMake(kMargin, CGRectGetMaxY(self.noteTextView.frame)+kGap, kLabelWidth+kMargin+kButtonWidth, kLabelHeight)];
    
    [self.datePicker setFrame:CGRectMake(0, SCREEN_HEIGHT-64, SCREEN_WIDTH, kDatePickerViewH)];
}

#pragma mark - privateMeth
-(void)handleCancelEvent:(id)sender{
    [self dismissViewControllerAnimated:YES completion:nil];
}

-(void)resetDatePicker{
    _isShowDatePicker = NO;
    [UIView animateWithDuration:0.25 animations:^{
        [_datePicker setFrame:CGRectMake(0, SCREEN_HEIGHT-64, SCREEN_WIDTH, kDatePickerViewH)];
    }];
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
    if (_isShowDatePicker) {
        [self resetDatePicker];
    }
}


-(void)handleDateButtonEvent{
    [self.view endEditing:YES];
    _isShowDatePicker = YES;
    [UIView animateWithDuration:0.25 animations:^{
        self.datePicker.frame=CGRectMake(0, SCREEN_HEIGHT-64-kDatePickerViewH, SCREEN_WIDTH, kDatePickerViewH);
    }];
}

-(void)dateChanged:(id)sender{
    UIDatePicker *picker = (UIDatePicker*)sender;
    NSDate *date = picker.date;
    NSDateFormatter *formatter = [self dateFormatter];
    NSString *string = [formatter stringFromDate:date];
    [self.dateButton setTitle:string forState:UIControlStateNormal];
}

-(void)clickSureButton{
    [self.view endEditing:YES];
    [self resetDatePicker];
    
    NSString *noteText = [self.noteTextView.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    if ([YWCommonTool isContainsEmoji:noteText]) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextCantContainEmoji, nil)];
        return;
    }
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"makeSureToGrabTroubleBill", nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"cancel", nil) style:UIAlertActionStyleCancel handler:nil]];
    [alert addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"sure", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSString *string = [NSString stringWithFormat:@"%@ 00:00:00",self.dateButton.titleLabel.text ];
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
        NSDate *date = [dateFormatter dateFromString:string];
        date = [YWCommonTool getNowDateFromatAnyDate:date];
        NSTimeInterval timeInterval = [date timeIntervalSince1970]*1000;
        [self postWithFinishDate:timeInterval note:noteText];
    }]];
    [self presentViewController:alert animated:YES completion:nil];
}


- (void)postWithFinishDate:(NSTimeInterval)finishDate note:(NSString*)note{
    NSDictionary *headersDic = [YWCommonTool addSubHttpHeadWithDic:[WMHttpTool shareHttpTool].HTTPHeaders];
    [WMHttpTool shareHttpTool].HTTPHeaders = headersDic;
    if (headersDic == nil) {return;}
    NSString * url = [NSString stringWithFormat:@"%@/%ld",[YWCommonTool grabTroubleBillUrl],(long)_reportTroubleModel.troubleId];
    NSDictionary* params = @{ @"cutoffTime" : @(finishDate),
                              @"demand" : note ?: @"" };
    YWLog(@"grabTroubleBill params:%@",params);
    [self.HUD show:YES];
    [[WMHttpTool shareHttpTool] postWithUrl:url params:params success:^(NSHTTPURLResponse* response, id json) {
        [self.HUD hide:YES];
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"grabTroubleBillSucceed", nil)];

        //返回的json是{}
        
//        YWTroubleMissionModelJson* troubleMissionJson = [YWTroubleMissionModelJson mj_objectWithKeyValues:json];
//        YWTroubleMissionModelApiJson * troubleJson = [YWTroubleMissionModelApiJson mj_objectWithKeyValues:json];
//        if (troubleMissionJson) {
//            //保存流转信息
//            [[YWCirculationManager shareManager] updateCirculationInfoWithArray:troubleMissionJson.circulationInfos];
//        }
//        _troubleMission.missionType = YWTroubleMissionTypeGrabBill;
//        _troubleMission.demand = note;
//        _troubleMission.cutoffTime = finishDate;
//        
//        YWHandler *handler = [[YWHandler alloc] init];
//        YWLoginUser *currentUser = [YWLoginTool loginUser];
//        handler.uniqueId = currentUser.uniqueId;
//        handler.userName = currentUser.userName;
//        handler.headIcon = currentUser.headIcon;
//        handler.mobile = currentUser.mobile;
//        _troubleMission.creator = handler;
//        _troubleMission.executor = handler;
//        _troubleMission.troubleStatus = YWTroubleMissionStatusAssign;
//        _troubleMission.finishTime = [[NSDate date] timeIntervalSince1970] * 1000;
//        [[YWMissionManager shareManager] saveMissionWithMissionArray:_troubleMission ? @[ _troubleMission ]:nil];
        YWHandler *handler = [[YWHandler alloc] init];
        YWLoginUser *currentUser = [YWLoginTool loginUser];
        handler.uniqueId = currentUser.uniqueId;
        handler.userName = currentUser.userName;
        handler.headIcon = currentUser.headIcon;
        handler.mobile = currentUser.mobile;
        _reportTroubleModel.troubleMission.creator = handler;
        //创建保存流转信息
        [[YWCirculationManager shareManager] createAndSaveLocalCirculationInfoWithType:YWCirculationInfoTypeAssignTroubleMission troubleId:_reportTroubleModel.troubleId recipient:handler note:note];
        //更新报障单状态
        [[YWReportTroubleManager shareManager] updateReportTroubleStatus:YWTroubleMissionStatusAssign troubleId:_reportTroubleModel.troubleId];
        //更新维修单状态
        [[YWTroubleMissionManager shareManager] updateTroubleMissionStatus:YWTroubleMissionStatusAssign troubleId:_reportTroubleModel.troubleId];
        //更新维修信息
//         [[YWTroubleMissionManager shareManager] updateTroubleMissionWithArray:troubleJson?@[troubleJson]:nil needUpdateReportTrouble:YES];
        [[YWEwinManager shareManager] subtractTotalCountWithType:YWUnReadCountTypeUnDistributionTroubleTotal];
        [[YWEwinManager shareManager] addTotalCountWithType:YWUnReadCountTypeFixTrouble];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [[NSNotificationCenter defaultCenter] postNotificationName:KPostGrabTroubleBillSuccessNotification object:nil];
            BOOL notFirstEnter = [[[NSUserDefaults standardUserDefaults] objectForKey:KNotFirstGrabTroubleBillSucceed] boolValue];
            if (!notFirstEnter) {
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"grabTroubleBillSucceed", nil) message:NSLocalizedString(KFirstGrabTroubleBillSucceedTips, nil) preferredStyle:UIAlertControllerStyleAlert];
                [alert addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"cancel", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    [self dismissViewControllerAnimated:YES completion:nil];
                }]];
                [alert addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"dontPromptAgain", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:KNotFirstGrabTroubleBillSucceed];
                    [[NSUserDefaults standardUserDefaults] synchronize];
                    [self dismissViewControllerAnimated:YES completion:nil];
                }]];
                [self presentViewController:alert animated:YES completion:nil];
            }else{
                [self dismissViewControllerAnimated:YES completion:nil];
            }
        });
        
    } failure:^(NSHTTPURLResponse* response, NSError* error) {
        YWLog(@"%s,error:%@", __func__, error.localizedDescription);
        [self.HUD hide:YES];
        NSInteger statusCode = response.statusCode;
        NSString *tips = nil;
        if (statusCode == 400 || statusCode == 304) {
            [[YWCirculationManager shareManager] requestCirculationInfoWithTroubleId:_reportTroubleModel.troubleId needTip:NO  WithComplete:nil];
        }
        if (statusCode == 400) {
            self.reportTroubleModel.troubleStatus = YWTroubleMissionStatusCancelPostTrouble;
            tips = NSLocalizedString(@"troubleBillHasCanceled", nil);
//            self.troubleMissionModel.troubleStatus = YWTroubleMissionStatusAssign;
//            tips = NSLocalizedString(kTextPendingTroubleFail, nil);
        }else if (statusCode == 304){
//            self.troubleMissionModel.troubleStatus = YWTroubleMissionStatusFinish;
            tips = NSLocalizedString(@"troubleMissionHasAssignedOrFinished", nil);
        }else{
            tips = NSLocalizedString(@"grabTroubleBillFailed", nil);
        }

        dispatch_async(dispatch_get_main_queue(), ^{
            if ([[WMHttpTool shareHttpTool] existenceNetwork]) {
                [[NSNotificationCenter defaultCenter] postNotificationName:KPostGrabTroubleBillFailNotification object:@(statusCode)];
            }
        });
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:tips message:nil preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"ok", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self dismissViewControllerAnimated:YES completion:nil];
        }]];
        [self presentViewController:alert animated:YES completion:nil];
    }];
}

#pragma mark - UIKeyboardNSNotification
- (void)keyboardWillShow:(NSNotification*)notification
{
    [self resetDatePicker];
    NSDictionary* info = [notification userInfo];
    NSValue* value = [info objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGSize keyboardSize = [value CGRectValue].size;
    CGFloat duration = [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    [self moveUpBgViewWithKeyboardHeight:keyboardSize.height animationDuration:duration];
}

- (void)keyboardWillHide:(NSNotification*)notification
{
    NSDictionary* info = [notification userInfo];
    CGFloat duration = [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    [self moveDownBgViewWithDuration:duration];
}
- (void)moveUpBgViewWithKeyboardHeight:(CGFloat)height animationDuration:(CGFloat)duration
{
    CGFloat bgViewMaxY = CGRectGetMaxY(self.bgView.frame);
    if (SCREEN_HEIGHT - bgViewMaxY >= height) {
        return;
    }
    [UIView animateWithDuration:duration animations:^{
        self.bgView.y = SCREEN_HEIGHT - self.bgView.height - height;
    }];
}

- (void)moveDownBgViewWithDuration:(CGFloat)duration
{
    if (originalBgViewY == self.bgView.y) {
        return;
    }
    [UIView animateWithDuration:duration animations:^{
        self.bgView.y = originalBgViewY;
    }];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    //键盘弹起的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    //键盘隐藏的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}
- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}

- (void)textViewDidChange:(UITextView *)textView{
    NSString *toBeString = textView.text;
    
    //获取高亮部分
    UITextRange *selectedRange = [textView markedTextRange];
    UITextPosition *position = [textView positionFromPosition:selectedRange.start offset:0];
    
    // 没有高亮选择的字，则对已输入的文字进行字数统计和限制
    if (!position)
    {
        if (toBeString.length > KNoteTextMax)
        {
            NSRange rangeIndex = [toBeString rangeOfComposedCharacterSequenceAtIndex:KNoteTextMax];
            if (rangeIndex.length == 1)
            {
                textView.text = [toBeString substringToIndex:KNoteTextMax];
            }
            else
            {
                NSRange rangeRange = [toBeString rangeOfComposedCharacterSequencesForRange:NSMakeRange(0, KNoteTextMax)];
                textView.text = [toBeString substringWithRange:rangeRange];
            }
        }
    }
    self.inputTextCount.text = [NSString stringWithFormat:@"%lu/100",(unsigned long)textView.text.length];
}

- (MBProgressHUD*)HUD
{
    if (!_HUD) {
        MBProgressHUD* hud = [[MBProgressHUD alloc] initWithView:self.view];
        hud.labelFont = kHUDLabelFont;
        hud.labelText = NSLocalizedString(kTextPendingTrouble, nil);
        hud.dimBackground = YES;
        //hud.animationType = MBProgressHUDAnimationZoom;
        _HUD = hud;
        _HUD.tag = kMBProgressHUDTag;
        [self.view addSubview:hud];
    }
    return _HUD;
}

@end
